<?php
/*
 * 字符串助手
 */
class Helper_String
{
	/**
	 * 过滤非法字符串
	 *
	 * @param string $str
	 * @return string
	 */
	public static function encode( $str )
	{
		return htmlspecialchars( $str );
	}
	
	/**
	 * 工具方法。未来应该抽出来才好
	 * 参数不要用引用 防止重复urlencode
	 * @param array $params
	 */
	public static function buildBaseString( $params )
	{
		if (!$params) return '';

		// Urlencode both keys and values
		$keys = self::urlencodeRfc3986(array_keys($params));
		$values = self::urlencodeRfc3986(array_values($params));
		$params = array_combine($keys, $values);

		// Parameters are sorted by name, using lexicographical byte value ordering.
		// Ref: Spec: 9.1.1 (1)
		uksort($params, 'strcmp');

		$pairs = array();
		foreach ($params as $parameter => $value)
		{
			if (is_array($value))
			{
				// If two or more parameters share the same name, they are sorted by their value
				// Ref: Spec: 9.1.1 (1)
				natsort($value);
				foreach ($value as $duplicate_value)
				{
					$pairs[] = $parameter . '=' . $duplicate_value;
				}
			}
			else
			
			{
				$pairs[] = $parameter . '=' . $value;
			}
		}
		// For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
		// Each name-value pair is separated by an '&' character (ASCII code 38)
		return implode('&', $pairs);
	}
	
	/**
	 * 对字符窜进行urlencode
	 *
	 * @param string $input
	 */
	public static function urlencodeRfc3986($input)
	{
		if (is_array( $input ) )
		{
			return array_map( array( 'self', 'urlencodeRfc3986' ), $input);
		}
		elseif ( is_scalar( $input ) )
		{
			return str_replace(
				'+',
				' ',
				str_replace('%7E', '~', rawurlencode($input))
			);
		}
		else
		{
			return '';
		}
	}

	/**
	* 截取字符串
	 */
	public static function subStr($str, $length, $append = TRUE, $htmlspecialchars = TRUE)
	{
		$str = mb_strimwidth($str, 0, $length, $append === TRUE ? '...' : '', 'UTF-8');

		if ($htmlspecialchars === TRUE)
		{
			return htmlspecialchars($str, ENT_QUOTES);
		}
		else
		{
			return $str;
		}
	}
    
    /**
     * 密码加密函数
     * @param string    $password
     * @param string    $key
     * @return string
     */
    public static function password_hash( $password , $key = null )
    {
        if( $key === null )
        { 
            $key = substr( md5( uniqid( rand() , true ) ) , 0 , 9 );
        }
        else
        {   
            $key = substr( $key , 0 , 9 );
        }
        
        return md5( $password . $key );
    }
}